package com.tangtang.security;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.*;

import com.tangtang.core.StringUtil;
import com.tangtang.security.service.UserService;
import com.tangtang.security.view.model.SysViewResourceRole;

/**
 * 
 * 此类在初始化时，应该取到所有资源及其对应角色的定义
 * 
 * @author Robin
 * 
 */
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource
{
	private static Map<String, HashSet<ConfigAttribute>>	resourceMap	= null;
	
	UserService												userService;
	
	public UserService getUserService()
	{
		return userService;
	}
	
	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}
	
	private void loadResourceDefine()
	{
		if (resourceMap == null)
		{
			resourceMap = new HashMap<String, HashSet<ConfigAttribute>>();
			List<SysViewResourceRole> resources = userService.getAllRoleResource();
			if (resources != null)
			{
				for (SysViewResourceRole sysViewResourceRole : resources)
				{
					ConfigAttribute ca = new SecurityConfig(sysViewResourceRole.getRoleId().toString());
					if (StringUtil.isNotBlank(sysViewResourceRole.getResourceUrl()))
					{
						if (resourceMap.containsKey(sysViewResourceRole.getResourceUrl()))
						{
							resourceMap.get(sysViewResourceRole.getResourceUrl()).add(ca);
						}
						else
						{
							HashSet<ConfigAttribute> set = new HashSet<ConfigAttribute>();
							set.add(ca);
							resourceMap.put(sysViewResourceRole.getResourceUrl(), set);
						}
					}
				}
			}
		}
	}
	
	// According to a URL, Find out permission configuration of this URL.
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException
	{
		loadResourceDefine();
		// guess object is a URL.
		HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext())
		{
			String resURL = ite.next();
			AntPathRequestMatcher urlMatcher = new AntPathRequestMatcher(resURL);
			if (urlMatcher.matches(request))
			{
				return resourceMap.get(resURL);
			}
		}
		return null;
	}
	
	public boolean supports(Class<?> clazz)
	{
		return true;
	}
	
	public Collection<ConfigAttribute> getAllConfigAttributes()
	{
		return null;
	}
	
}
